package csc.fresher.utils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.PreparedStatement;

import org.apache.log4j.Logger;

public class DatabaseUtil {

	public static ResultSet executeQuery(PreparedStatement ps, Connection con, String sql,
			Object[] params) {
		ResultSet rs = null;
		try {
			ps = con.prepareStatement(sql);
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					ps.setObject(i + 1, params[i]);
				}
			}
			rs = ps.executeQuery();
			return rs;
		} catch (SQLException e) {

			e.printStackTrace();
		}
		return null;
	}

	public static int executeUpdate(PreparedStatement ps,Connection con, String sql, Object[] params) {
		int r = -1;
		try {
			con.setAutoCommit(false);
			ps = con.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
			r = ps.executeUpdate();
			con.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				con.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			return r;
		}
		return r;
	}

	public static void closeConnection(Connection connection, PreparedStatement preparedStatement, Logger logger){
		try {
			if (preparedStatement != null) {
				preparedStatement.close();
			}
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	
	public static void closeResultSetConnection(Connection connection, PreparedStatement preparedStatement, ResultSet rs, Logger logger){
		try {
			if (rs != null) {
				rs.close();
			}
			if (preparedStatement != null) {
				preparedStatement.close();
			}
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
}
